package com.business_clean.app.uitl;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.business_clean.app.network.NetUrl;
import com.business_clean.data.initconfig.QiniuInfo;
import com.luck.picture.lib.entity.LocalMedia;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.functions.Consumer;
import me.hgj.mvvmhelper.base.Ktx;
import me.hgj.mvvmhelper.ext.LogExtKt;
import rxhttp.wrapper.param.RxHttp;

public class UploadFileHelper {

    private static final String TAG = "UploadFileHelper";
    private static final String QINIU_HOST_NAME = NetUrl.AUDIO_URL;

    public static final String PATH_HEADER_CAMERA = "camera/";

    public static final String PATH_HEADER_CUSTOM = "custom/";
    public static final String PATH_HEADER_PROJECT = "project/";
    public static final String PATH_HEADER_PERSONNEL = "personnel/";

    public static final String PATH_HEADER_MY = "my/";

    private static UploadFileHelper uploadFileHelper;

    private UploadManager uploadManager;


    private UploadFileHelper() {
        Configuration config = new Configuration.Builder()
                .connectTimeout(120) // 链接超时。默认90秒
                .useHttps(true) // 是否使用https上传域名
                .useConcurrentResumeUpload(true) // 使用并发上传
                .concurrentTaskCount(9) // 并发上传线程数量为3
                .responseTimeout(30) // 服务器响应超时。默认90秒
                .build();
        uploadManager = new UploadManager(config);
    }

    public static UploadFileHelper getInstance() {
        if (uploadFileHelper == null) {
            uploadFileHelper = new UploadFileHelper();
        }
        return uploadFileHelper;
    }


    public void uploadFiles(Context mContext, ArrayList<String> result, String space, UploadListener listener) {
        LogExtKt.logE("拿到的图片列表->" + result.size(), TAG);
        RxHttp.get(NetUrl.GET_QINIU_TOKEN).asResponse(QiniuInfo.class)
                .subscribe(new Consumer<QiniuInfo>() {
                    @Override
                    public void accept(QiniuInfo qiniuInfo) throws Throwable {
                        for (String media : result) {
                            startUploadFile(mContext, qiniuInfo.getToken(), space, listener, new File(media));
                        }
                    }
                });
    }

    public void uploadPictures(Context mContext, String path, String space, UploadListener listener) {
        if (TextUtils.isEmpty(path)) {
            if (listener != null) {
                listener.onUploadFailed("无效的文件");
            }
        }
        RxHttp.get(NetUrl.GET_QINIU_TOKEN).asResponse(QiniuInfo.class)
                .subscribe(new Consumer<QiniuInfo>() {
                    @Override
                    public void accept(QiniuInfo qiniuInfo) throws Throwable {
                        startUploadFile(mContext, qiniuInfo.getToken(), space, listener, new File(path));
                    }
                });
    }


    private void startUploadFile(Context mContext, String token, String space, UploadListener listener, File file) {
        if (!TextUtils.isEmpty(token)) {
            uploadFileQiniu(mContext, file, token, space, listener);
        } else {
            ToastUtil.show("上传失败，稍后再尝试");
        }
    }

    private void uploadFileQiniu(Context mContext, File file, String token, String space, UploadListener listener) {
        LogExtKt.logE("准备开始上传了", TAG);
        LogExtKt.logE("开始上传的任务了", TAG);
        String name = file.getName();
        String filename = space + TimeUtils.date2String(TimeUtils.getNowDate(), "yyyyMMdd") + "/" + EncryptUtils.encryptMD5ToString(TimeUtils.getNowMills() + name);
        UploadOptions options = new UploadOptions(null, null, false, new UpProgressHandler() {
            @Override
            public void progress(String key, double percent) {
                Log.e(TAG, "上传的进度" + (int) (percent * 100));
                if (listener != null) {
                    listener.onUploadProgress((int) (percent * 100));
                }
            }
        }, null);
        uploadManager.put(file, filename, token, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject response) {
                Log.e(TAG, "Upload info --> " + info);
                Log.e(TAG, "Upload info -->" + getKeyUrl(response));
                if (info.isOK()) {
                    if (listener != null) {
                        listener.onUploadSuccess(getKeyUrl(response));
                    }
                    Log.e(TAG, "uploadSuccess --> " + getKeyUrl(response));
                } else {
                    if (listener != null) {
                        listener.onUploadFailed(info.error);
                    }
                    Log.e(TAG, "上传失败" + getKeyUrl(response));
                }
            }
        }, options);
    }

    private static String getKeyUrl(JSONObject response) {
        if (response == null) {
            return null;
        }
        String url = null;
        try {
            url = QINIU_HOST_NAME + String.valueOf(response.get("key"));
        } catch (JSONException e) {
            Log.e(TAG, "获取七牛返回的Url" + e);
        }
        return url;
    }

    public interface UploadListener {
        void onUploadSuccess(String response);

        void onUploadFailed(String error);

        void onUploadProgress(int progress);

    }

}
